import 'package:flutter/cupertino.dart';
import 'package:oktoast/oktoast.dart';
import 'package:wan_android_flutter/repository/Api.dart';

import '../../constants.dart';
import '../../repository/datas/user_info_model.dart';
import '../../utils/sp_utils.dart';

class AuthViewModel with ChangeNotifier{
  RegisterInfo registerInfo = RegisterInfo();
  LoginInfo loginInfo = LoginInfo();

  Future<bool?> register() async{
    if(registerInfo.name!=null&&registerInfo.password!=null&&registerInfo.rePassword!=null && registerInfo.password == registerInfo.rePassword ){
      if((registerInfo.name?.length ?? 0 )<3){
        showToast("账号长度必须大于3位");
        return false;
      }
      if((registerInfo.password?.length ?? 0 )<6){
        showToast("密码长度必须大于6位");
        return false;
      }
      dynamic callback = await Api.instance().register(name:registerInfo.name,password:registerInfo.password,rePassword:registerInfo.rePassword);
      if(callback is bool){
        return callback;
      }
      return true;
    }
    showToast("输入不能为空，且俩次密码必须得一致");
    return false;
  }
  void setLoginInfo({String? name,String? password}){
    if(name!=null){
      loginInfo.name=name;
    }
    if(password!=null){
      loginInfo.password=password;
    }
  }
  Future<bool?> login() async{
    print(loginInfo.toString());
    if(loginInfo.name!=null&&loginInfo.password!=null){
      if((loginInfo.name?.length ?? 0 )<3){
        showToast("账号长度必须大于3位");
        return false;
      }
      if((loginInfo.password?.length ?? 0 )<6){
        showToast("密码长度必须大于6位");
        return false;
      }
      UserInfoModel callback = await Api.instance().login(name:loginInfo.name,password:loginInfo.password);
      if(callback.username!=null && callback.username?.isNotEmpty ==true){
        //保存用户名
        SpUtils.saveString(Constants.SP_USER_NAME, callback.username ?? "");
        return true;
      }
      showToast("登录失败");
      return false;
    }
    showToast("输入不能为空");
    return false;
  }

}
class RegisterInfo{
  String? name;
  String? password;
  String? rePassword;
}

class LoginInfo{
  String? name;
  String? password;
}